package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.RiderLocation;
import com.draven.mall.service.RiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;

/**
 * 骑手位置上报控制器
 */
@RestController
@RequestMapping("/api/rider/location")
public class RiderLocationController {

    private static final Logger log = LoggerFactory.getLogger(RiderLocationController.class);

    @Autowired
    private RiderService riderService;

    /**
     * 上报骑手位置
     */
    @PostMapping("/update")
    public ApiResponse updateLocation(@RequestBody Map<String, Object> location) {
        try {
            log.info("上报骑手位置: {}", location);
            
            // 从请求体中获取位置信息
            Long riderId = Long.valueOf(location.get("riderId").toString());
            Double latitude = Double.valueOf(location.get("latitude").toString());
            Double longitude = Double.valueOf(location.get("longitude").toString());
            Long timestamp = Long.valueOf(location.get("timestamp").toString());
            
            // 创建位置信息对象
            RiderLocation riderLocation = new RiderLocation();
            riderLocation.setRiderId(riderId);
            riderLocation.setLatitude(latitude);
            riderLocation.setLongitude(longitude);
            riderLocation.setUpdateTime(timestamp);
            
            // 保存位置信息（这里可以调用服务层方法）
            // riderService.updateLocation(riderLocation);
            
            return ApiResponse.success("位置上报成功");
        } catch (Exception e) {
            log.error("位置上报失败", e);
            return ApiResponse.error("位置上报失败: " + e.getMessage());
        }
    }

    /**
     * 获取骑手位置
     */
    @GetMapping("/get")
    public ApiResponse getRiderLocation(@RequestParam Long riderId) {
        try {
            // 模拟从数据库获取位置信息
            // 实际项目中应该从数据库查询
            HashMap<String, Object> location = new HashMap<>();
            location.put("riderId", riderId);
            location.put("latitude", 30.274085);
            location.put("longitude", 120.155070);
            location.put("updateTime", System.currentTimeMillis() - 60000); // 假设1分钟前上报的位置
            
            return ApiResponse.success(location);
        } catch (Exception e) {
            log.error("获取骑手位置失败", e);
            return ApiResponse.error("获取骑手位置失败: " + e.getMessage());
        }
    }
} 